package com.lock;

import org.omg.CORBA.IDLTypeOperations;

import java.util.concurrent.TimeUnit;
import java.util.concurrent.atomic.AtomicReference;

/**
 * 自旋锁
 */
public class SpinlockDemo {

    AtomicReference<Thread> atomicReference = new AtomicReference<>();

    public static void main(String[] args) {
        SpinlockDemo lock = new SpinlockDemo();

        new Thread(()->{
            lock.myLock();     //T1加锁之后之后，方法里面拿到thread
            try {
                TimeUnit.SECONDS.sleep(4);
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
            lock.unLock();
        },"T1").start();

        new Thread(()->{  //T1解锁之前，T2会一直自旋转，因为一直没有达到预期值
            lock.myLock();
            try {
                TimeUnit.SECONDS.sleep(2);
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
            lock.unLock();

        },"T2").start();
    }



    //加锁
    public void myLock() {
        Thread thread = Thread.currentThread();
        System.out.println(Thread.currentThread().getName() + "===> ,MyLock");

        while (!atomicReference.compareAndSet(null, thread)) {

        };
    }

    //解锁
    public void unLock() {

        Thread thread = Thread.currentThread();
        System.out.println(Thread.currentThread().getName() + "解锁方法");
        atomicReference.compareAndSet(thread, null);
    }


}
